import React, { useMemo, useState, useEffect } from 'react';
import { filter_row, loc_str, FindBarBase, useCmd, WaitUmd, show_mt, loc_year, utc_8, d_sort, save_data, useHigh, MainView, Btn,
    GridTable, cline, urlTb, is_empty, for_obj, loc } from 'sui';
import { get_init } from 'trace/cmd';
import { utc_offset } from 'cache';
import { load_col } from '../task/cmd';
import { load_tech } from 'task/cmd';

const TraceView = () => {
    const [col, setCol] = useState();
    const [tech, setTech] = useState();
    const [main, setMain] = useState();
    const [opt_find, optFind] = useState();
    const umd = useCmd(null, "trace");
    const [high] = useHigh(140, 100);

    useEffect(() => {
        get_init(optFind)
        setMain(null);
        load_col(setCol);
        load_tech(v => {
            v.forEach(d => d["id"] = d.sn);
            setTech(v);
        });
    }, []);

    const getTab = (s, e) => {
        let sy = loc_year(s);
        sy = parseInt(sy, 10);

        let ey = loc_year(e);
        ey = parseInt(ey, 10);

        const ret = [];

        for (let t = sy; t <= ey; t++) {
            ret.push(`sale${t}`);
        }

        return ret;
    };

    const hfind = (value) => {
        const opt = [];
        const utc = utc_offset();

        for_obj(value, (k, v) => {
            if (k === "t_start" || k === "t_end") {
                return;
            }

            if (!v) {
                return;
            }

            if (k === "time") {
                opt.push({ge: "time", v: loc_str(value["t_start"]), utc: utc});
                opt.push({le: "time", v: loc_str(value["t_end"]), utc: utc});
                return;
            }

            opt.push({eq: k, v: v});
        });

        if (is_empty(opt)) {
            alert(loc("l_307"));
            return;
        }

        opt.push({eq: "line", v: cline()});

        let tab = getTab(value["t_start"], value["t_end"]);

        umd.startWait();

        const cmd = {
            n: tab.join(","),
            obj: "*",
            opt: {desc: true, and: opt}
        };


        urlTb(null, "get", cmd,
            r => {
                const ret = [];
                const utc = utc_offset();

                tab.forEach(d => {
                    if (!r[d]) {
                        return;
                    }

                    const data = r[d]["data"];
                    if (!data) {
                        return;
                    }

                    data.forEach(t => {
                        const tmp = t["time"];
                        t["time"] = utc_8(tmp, utc);

                        ret.push(t);
                    });
                });

                d_sort(ret, "time", true);

                ret.forEach((d, i) => d["index"] = i + 1);

                setMain(ret);

                umd.endWait();
            },
            e => {
                setMain(null);
                umd.endWait();
            });
    };

    const filteredRows = useMemo(() => {
        if (is_empty(main) || is_empty(col)) {
            return null;
        }

        const lst = col.map(d => d.key);

        return filter_row(main, lst, umd.filter);
    }, [col, main, umd.filter]);

    const Right = () => {
        return (
            <div className="inline-flex items-center">
                <Btn hcmd={hExport} className="ml-4">{loc("l_298")}</Btn>
            </div>
        );
    };

    const hclear = () => get_init(optFind);

    const getCtl = () => {
        return {
            ctl: [
                {sn: "psn", name: loc("l_518")},
                {sn: "tsn", name: loc("l_309"), ctl: "IkFind", lst: tech},
                {sn: "time", name: loc("l_308"), ctl: "IkFindDate", start: "t_start", end: "t_end"},
            ]
        };
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_101"), key: 'time', width: 180, frozen: true},
        ];

        col.forEach(d => show_mt(tmp, d, 160));

        return tmp;
    };

    const hExport = () => {
        save_data(main, getCol(), `${loc("l_860")}`, umd);
    };

    return (
        <MainView>
            <FindBarBase left={loc("l_860")} right={<Right/>} hcmd={hfind} data={getCtl()} hclear={hclear} cur={opt_find} hfilter={umd.setFilter}/>
            <GridTable col={getCol()} row={filteredRows} high={high - 50}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {TraceView};
